package com.zenithmind.document.pojo.vo;

import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

/**
 * 文档权限VO
 * 遵循单一职责原则：专注于权限数据展示
 * 遵循开闭原则：支持字段的扩展
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Data
@Schema(description = "文档权限VO")
public class DocumentPermissionVO {

    @Schema(description = "权限ID", example = "perm123456")
    private String id;

    @Schema(description = "文档ID", example = "doc123456")
    private String documentId;

    @Schema(description = "文档标题", example = "项目需求文档")
    private String documentTitle;

    @Schema(description = "文档类型", example = "PDF")
    private String documentType;

    @Schema(description = "目标类型", example = "USER")
    private String targetType;

    @Schema(description = "目标类型描述", example = "用户")
    private String targetTypeDesc;

    @Schema(description = "目标ID", example = "user123456")
    private String targetId;

    @Schema(description = "目标名称", example = "张三")
    private String targetName;

    @Schema(description = "目标头像", example = "https://example.com/avatar.jpg")
    private String targetAvatar;

    @Schema(description = "目标邮箱", example = "zhangsan@example.com")
    private String targetEmail;

    @Schema(description = "目标部门", example = "技术部")
    private String targetDepartment;

    @Schema(description = "权限类型", example = "READ")
    private String permissionType;

    @Schema(description = "权限类型描述", example = "读取")
    private String permissionTypeDesc;

    @Schema(description = "权限值", example = "ALLOW")
    private String permissionValue;

    @Schema(description = "权限值描述", example = "允许")
    private String permissionValueDesc;

    @Schema(description = "权限级别", example = "2")
    private Integer permissionLevel;

    @Schema(description = "权限级别描述", example = "写入级别")
    private String permissionLevelDesc;

    @Schema(description = "权限范围", example = "DOCUMENT")
    private String permissionScope;

    @Schema(description = "权限范围描述", example = "文档级别")
    private String permissionScopeDesc;

    @Schema(description = "权限条件", example = "{\"timeRange\": \"09:00-18:00\"}")
    private String permissionCondition;

    @Schema(description = "权限条件描述", example = "工作时间内有效")
    private String permissionConditionDesc;

    @Schema(description = "是否继承", example = "true")
    private Boolean isInherited;

    @Schema(description = "继承来源", example = "角色权限")
    private String inheritanceSource;

    @Schema(description = "父权限ID", example = "perm123456")
    private String parentPermissionId;

    @Schema(description = "父权限描述", example = "部门管理员权限")
    private String parentPermissionDesc;

    @Schema(description = "优先级", example = "200")
    private Integer priority;

    @Schema(description = "优先级描述", example = "高优先级")
    private String priorityDesc;

    @Schema(description = "生效时间", example = "2025-01-09T00:00:00")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime effectiveTime;

    @Schema(description = "过期时间", example = "2025-12-31T23:59:59")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime expirationTime;

    @Schema(description = "剩余有效期", example = "30天")
    private String remainingValidPeriod;

    @Schema(description = "授权人ID", example = "admin123")
    private String grantorId;

    @Schema(description = "授权人姓名", example = "管理员")
    private String grantorName;

    @Schema(description = "授权人头像", example = "https://example.com/admin-avatar.jpg")
    private String grantorAvatar;

    @Schema(description = "授权原因", example = "项目协作需要")
    private String grantReason;

    @Schema(description = "权限标签", example = "临时权限,项目相关")
    private String permissionTags;

    @Schema(description = "权限标签列表", example = "[\"临时权限\", \"项目相关\"]")
    private String[] permissionTagArray;

    @Schema(description = "是否可委托", example = "false")
    private Boolean isDelegatable;

    @Schema(description = "最大委托层级", example = "2")
    private Integer maxDelegationLevel;

    @Schema(description = "当前委托层级", example = "1")
    private Integer currentDelegationLevel;

    @Schema(description = "委托限制", example = "{\"maxUsers\": 5}")
    private String delegationRestrictions;

    @Schema(description = "委托限制描述", example = "最多委托给5个用户")
    private String delegationRestrictionsDesc;

    @Schema(description = "审批状态", example = "APPROVED")
    private String approvalStatus;

    @Schema(description = "审批状态描述", example = "已批准")
    private String approvalStatusDesc;

    @Schema(description = "审批人ID", example = "approver123")
    private String approverId;

    @Schema(description = "审批人姓名", example = "审批员")
    private String approverName;

    @Schema(description = "审批时间", example = "2025-01-09T10:00:00")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime approvalTime;

    @Schema(description = "审批意见", example = "同意授权")
    private String approvalComment;

    @Schema(description = "权限描述", example = "允许查看和编辑项目文档")
    private String description;

    @Schema(description = "扩展属性", example = "{\"department\": \"IT\"}")
    private String extendedProperties;

    @Schema(description = "备注", example = "临时权限，项目结束后自动回收")
    private String remarks;

    @Schema(description = "是否启用", example = "true")
    private Boolean isEnabled;

    @Schema(description = "状态", example = "ACTIVE")
    private String status;

    @Schema(description = "状态描述", example = "活跃")
    private String statusDesc;

    @Schema(description = "是否已过期", example = "false")
    private Boolean isExpired;

    @Schema(description = "是否即将过期", example = "false")
    private Boolean isExpiringSoon;

    @Schema(description = "是否临时权限", example = "true")
    private Boolean isTemporary;

    @Schema(description = "是否有效", example = "true")
    private Boolean isEffective;

    @Schema(description = "权限强度", example = "MEDIUM", allowableValues = {"LOW", "MEDIUM", "HIGH", "CRITICAL"})
    private String permissionStrength;

    @Schema(description = "风险等级", example = "LOW", allowableValues = {"LOW", "MEDIUM", "HIGH", "CRITICAL"})
    private String riskLevel;

    @Schema(description = "使用次数", example = "15")
    private Integer usageCount;

    @Schema(description = "最后使用时间", example = "2025-01-09T15:30:00")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime lastUsedTime;

    @Schema(description = "创建时间", example = "2025-01-09T10:00:00")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime createTime;

    @Schema(description = "更新时间", example = "2025-01-09T10:30:00")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime updateTime;

    /**
     * 获取目标类型描述
     */
    public String getTargetTypeDescription() {
        if (targetType == null) return "";
        
        switch (targetType.toUpperCase()) {
            case "USER": return "用户";
            case "ROLE": return "角色";
            case "GROUP": return "用户组";
            case "DEPARTMENT": return "部门";
            default: return targetType;
        }
    }

    /**
     * 获取权限类型描述
     */
    public String getPermissionTypeDescription() {
        if (permissionType == null) return "";
        
        switch (permissionType.toLowerCase()) {
            case "read": return "读取";
            case "write": return "写入";
            case "delete": return "删除";
            case "share": return "分享";
            case "admin": return "管理";
            default: return permissionType;
        }
    }

    /**
     * 获取权限值描述
     */
    public String getPermissionValueDescription() {
        if (permissionValue == null) return "";
        
        switch (permissionValue.toUpperCase()) {
            case "ALLOW": return "允许";
            case "DENY": return "拒绝";
            case "INHERIT": return "继承";
            default: return permissionValue;
        }
    }

    /**
     * 获取权限级别描述
     */
    public String getPermissionLevelDescription() {
        if (permissionLevel == null) return "";
        
        switch (permissionLevel) {
            case 1: return "读取级别";
            case 2: return "写入级别";
            case 3: return "删除级别";
            case 4: return "分享级别";
            case 5: return "管理级别";
            default: return "未知级别";
        }
    }

    /**
     * 获取审批状态描述
     */
    public String getApprovalStatusDescription() {
        if (approvalStatus == null) return "";
        
        switch (approvalStatus.toUpperCase()) {
            case "PENDING": return "待审批";
            case "APPROVED": return "已批准";
            case "REJECTED": return "已拒绝";
            case "REVOKED": return "已撤销";
            default: return approvalStatus;
        }
    }

    /**
     * 获取状态描述
     */
    public String getStatusDescription() {
        if (status == null) return "";
        
        switch (status.toUpperCase()) {
            case "ACTIVE": return "活跃";
            case "INACTIVE": return "非活跃";
            case "SUSPENDED": return "已暂停";
            case "EXPIRED": return "已过期";
            default: return status;
        }
    }

    /**
     * 计算剩余有效期
     */
    public String calculateRemainingValidPeriod() {
        if (expirationTime == null) {
            return "永久有效";
        }
        
        LocalDateTime now = LocalDateTime.now();
        if (expirationTime.isBefore(now)) {
            return "已过期";
        }
        
        long days = ChronoUnit.DAYS.between(now, expirationTime);
        long hours = ChronoUnit.HOURS.between(now, expirationTime) % 24;
        
        if (days > 0) {
            return days + "天" + (hours > 0 ? hours + "小时" : "");
        } else if (hours > 0) {
            return hours + "小时";
        } else {
            long minutes = ChronoUnit.MINUTES.between(now, expirationTime);
            return minutes + "分钟";
        }
    }

    /**
     * 判断是否已过期
     */
    public boolean checkIsExpired() {
        return expirationTime != null && expirationTime.isBefore(LocalDateTime.now());
    }

    /**
     * 判断是否即将过期（7天内）
     */
    public boolean checkIsExpiringSoon() {
        if (expirationTime == null) return false;
        
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime sevenDaysLater = now.plusDays(7);
        
        return expirationTime.isAfter(now) && expirationTime.isBefore(sevenDaysLater);
    }

    /**
     * 判断是否为临时权限
     */
    public boolean checkIsTemporary() {
        return expirationTime != null;
    }

    /**
     * 判断是否有效
     */
    public boolean checkIsEffective() {
        LocalDateTime now = LocalDateTime.now();
        boolean afterEffective = effectiveTime == null || !effectiveTime.isAfter(now);
        boolean beforeExpiration = expirationTime == null || !expirationTime.isBefore(now);
        boolean isActive = "ACTIVE".equalsIgnoreCase(status);
        boolean isApproved = "APPROVED".equalsIgnoreCase(approvalStatus);
        boolean isEnabledFlag = isEnabled == null || isEnabled;
        
        return afterEffective && beforeExpiration && isActive && isApproved && isEnabledFlag;
    }

    /**
     * 获取权限强度
     */
    public String calculatePermissionStrength() {
        if (permissionLevel == null) return "LOW";
        
        switch (permissionLevel) {
            case 1: return "LOW";
            case 2: return "MEDIUM";
            case 3: case 4: return "HIGH";
            case 5: return "CRITICAL";
            default: return "LOW";
        }
    }

    /**
     * 获取风险等级
     */
    public String calculateRiskLevel() {
        String strength = calculatePermissionStrength();
        boolean isTemporaryPerm = checkIsTemporary();
        boolean hasCondition = permissionCondition != null && !permissionCondition.trim().isEmpty();
        
        if ("CRITICAL".equals(strength)) {
            return isTemporaryPerm && hasCondition ? "HIGH" : "CRITICAL";
        } else if ("HIGH".equals(strength)) {
            return isTemporaryPerm && hasCondition ? "MEDIUM" : "HIGH";
        } else if ("MEDIUM".equals(strength)) {
            return hasCondition ? "LOW" : "MEDIUM";
        } else {
            return "LOW";
        }
    }

    /**
     * 获取权限标签数组
     */
    public String[] getPermissionTagArray() {
        if (permissionTags == null || permissionTags.trim().isEmpty()) {
            return new String[0];
        }
        return permissionTags.split(",");
    }

    /**
     * 判断是否为高权限
     */
    public boolean isHighPermission() {
        return permissionLevel != null && permissionLevel >= 3;
    }

    /**
     * 判断是否需要审批
     */
    public boolean needsApproval() {
        return "PENDING".equalsIgnoreCase(approvalStatus);
    }

    /**
     * 判断是否可以委托
     */
    public boolean canDelegate() {
        return isDelegatable != null && isDelegatable && 
               maxDelegationLevel != null && maxDelegationLevel > 0 &&
               (currentDelegationLevel == null || currentDelegationLevel < maxDelegationLevel);
    }
}
